<template>
    <div class="container">
        <div class="tabs mb-4">
            <draggable :list="workbenches" itemKey="id" class="items" @end="saveSort">
                <template #item="{ element: item, idx: index }">
                    <div @click="selectItem(item)" class="tab-item cursor-pointer" :class="{ active: current.id == item.id }">
                        <el-icon class="move"><Rank /></el-icon>
                        <span>{{ item.name }}</span>
                        <el-popover v-if="item.type == 'personal'">
                            <template #reference>
                                <el-icon class="more"><MoreFilled /></el-icon>
                            </template>

                            <div class="menus lh-3">
                                <div @click="goEdit(item)">编辑</div>
                                <div @click="rename(item)">重命名</div>
                                <div @click="doDelete(item, idx)">删除</div>
                            </div>
                        </el-popover>
                    </div>
                </template>
            </draggable>
            <el-link class="ml-2 cursor-pointer" type="primary" icon="Plus" @click="addWorkbench"></el-link>
        </div>
        <div class="preview" :class="{ fullscreen }">
            <Preview :config="current.publishedConfig" v-if="current.publishedConfig" :key="current.id" />
        </div>
        
        <el-icon class="fullscreen-icon" @click="setFullscreen"><FullScreen /></el-icon>
    </div>
</template>
<script setup>
import { onMounted, onUnmounted } from "vue";
import Preview from "./design/preview.vue";
import defConfig from "./design/example/default.js";
import * as _ from "lodash";
import { useRouter } from "vue-router";
import draggable from "vuedraggable";
import { useSysStore } from "@/store/index.js";
import { ElMessage } from "element-plus";

const workbenches = ref([]);
const current = ref({});
const router = useRouter();
const sysStore = useSysStore();
const userInfo = computed(sysStore.getUserInfo);
const fullscreen = ref(false);

onMounted(() => {
    load();
    window.addEventListener("resize", windowResize);
});

onUnmounted(() => {
    window.removeEventListener("resize", windowResize);
});

function windowResize() {
    let widthDis = Math.abs(window.innerWidth - screen.width);
    let heightDis = Math.abs(window.innerHeight - screen.height);
    let isFullscreen = false;
    if (widthDis < 10 && heightDis < 10) {
        isFullscreen = true;
    }
    fullscreen.value = isFullscreen;
}

function load() {
    app.https.get("/sys/workbench/user").then((resp) => {
        resp.forEach((item) => {
            if (!item.publishedConfig) {
                item.publishedConfig = _.cloneDeep(defConfig);
            }
        });

        // 如果用户有调整顺序，则以用户调整的顺序为准
        let ids = userInfo.value.metadata?.workbenchIds;
        if (ids) {
            let items = [];
            let itemMap = {};
            resp.forEach((item) => {
                itemMap[item.id] = item;
            });
            ids.forEach((id) => {
                let item = itemMap[id];
                if (item) {
                    items.push(item);
                }
            });

            // 补充未配置到个性化配置中的记录
            resp.forEach((item) => {
                if (!ids.includes(item.id)) {
                    items.push(item);
                }
            });

            workbenches.value = items;
            current.value = items[0];
        } else {
            workbenches.value = resp;
            current.value = resp[0];
        }
    });
}

function selectItem(item) {
    current.value = item;
}

function addWorkbench() {
    app.prompt("请输入工作台名称", { inputValue: "个人工作台" }).then(({ value, action }) => {
        if (action != "confirm") {
            return;
        }

        app.https.post("/sys/workbench/add", { name: value, type: "personal", status: "draft" }).then(() => {
            app.success();
            load();
        });
    });
}

function rename(item) {
    app.prompt("工作台名称", { inputValue: item.name }).then(({ value, action }) => {
        if (action != "confirm") {
            return;
        }

        if (!value) {
            return;
        }

        app.https.put("/sys/workbench/update", { id: item.id, name: value }).then(() => {
            app.success();
            item.name = value;
        });
    });
}

function goEdit(item) {
    router.push("/workbench/design/" + item.id);
}

function doDelete(item, idx) {
    app.confirm("确定删除当前工作台？").then(() => {
        app.https.del("/sys/workbench/delete/" + item.id).then(() => {
            app.success();
            workbenches.value.splice(idx, 1);
        });
    });
}

// 保存工作台排序
function saveSort() {
    // 存储到用户个性化配置中
    let metadata = userInfo.value.metadata;
    metadata.workbenchIds = workbenches.value.map((item) => item.id);
    app.https.post("/sys/user/update-mine", { metadata }).then(() => {
        sysStore.setUserInfo(userInfo.value);
    });
}

function setFullscreen() {
    fullscreen.value = true;
    document.documentElement.requestFullscreen();
}
</script>

<style lang="scss" scoped>
.container {
    position: relative;

    .fullscreen-icon {
        position: absolute;
        right: 0px;
        top: 20px;
        cursor: pointer;
    }

    .preview.fullscreen {
        width: 100vw;
        height: 100vw;
        position: fixed;
        left: 0;
        top: 0;
        z-index: 100;
        background: var(--sub_bg_color);
        padding: 16px;
        box-sizing: border-box;
    }
}

.tabs {
    color: var(--follow_font_color);
    .items {
        display: inline-block;
    }

    .tab-item {
        line-height: 34px;
        display: inline-block;
        padding: 0 30px;
        border: 1px solid var(--main_border_color);
        background: var(--follow_bg_color);
        position: relative;

        .more {
            transform: rotate(90deg);
            font-size: 12px;
            position: absolute;
            right: 4px;
            top: 10px;
            color: var(--reverse_sub_font_color);
            display: none;
        }

        .move {
            font-size: 12px;
            position: absolute;
            left: 4px;
            top: 10px;
            color: var(--reverse_sub_font_color);
            display: none;
        }

        &.active {
            font-weight: bold;
            color: var(--primary_color);
            background: var(--main_bg_color);
            border-top: 2px solid var(--primary_color);
        }

        &:hover {
            .more,
            .move {
                display: inherit;
            }
        }
    }
}

.menus {
    > div {
        padding: 0 10px;
        cursor: pointer;

        &:hover {
            background: var(--primary_color);
            color: #fff;
        }
    }
}
</style>
